home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14584 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: news.panther.net!nemesis!hammy!not-for-mail
  2. From: gordon@sneaky.lerctr.org (Gordon Burditt)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Check if a file exists?
  5. Date: 15 Apr 1996 16:50:38 -0500
  6. Organization: What organization?
  7. Message-ID: <4kugbe$qi1@hammy.lonestar.org>
  8. References: <4kp7pg$upe@news-s01.ny.us.ibm.net> <4ktl40$b76@texas.nwlink.com>
  9. NNTP-Posting-Host: news.hammy.lonestar.org
  10.  
  11. >Use rename():
  12.  
  13. >You could try to rename it, and if that fails it's not there,
  14. >if it works it exists, and then you can rename it back.
  15.  
  16. It might fail for a number of other reasons, such as a poor
  17. choice of destination filename, or lack of write permission in
  18. the directory.
  19.  
  20. >Or, you can create a temporary file, try to rename it to the
  21. >name of the file you're testing, if it fails it exists, and
  22. >if it works it wasn't there, and then you can rename it back.
  23.  
  24. Careful.  If you create a temporary file, try to rename it to
  25. the name of the file you're testing, it might SUCCEED if the
  26. new name exists, and you've just wiped out the file of interest, 
  27. and replaced it with the temporary file.  ANSI C leaves
  28. implementation-defined the issue of whether renaming a file
  29. to another existing file fails or succeeds.  UNIX systems usually
  30. let it succeed.
  31.  
  32. >This should be faster than fopen, but you would need to have
  33. >write access to all the files you're testing.
  34.  
  35. It isn't at all obvious to me that rename() should be faster than
  36. fopen().  It especially isn't in the case where you have allowed
  37. a UNIX directory to accumulate way too many tens of thousands of
  38. files, and a directory search takes minutes.  (fopen would scan
  39. the directory once, stopping when it found the file, and rename
  40. would have to scan the whole directory looking for an entry with
  41. the new name, and it likely does a scan for the old name as well).
  42.  
  43. In the examples above, you require rename and delete access to
  44. the files, which need not involve write access.  Under UNIX,
  45. you only require write and search access to the directory,
  46. and NO access to the files themselves.
  47.  
  48. The UNIX examples above are not supposed to be an example of the
  49. way it has to be, but only an example of the way it CAN be as
  50. permitted by ANSI C.
  51.  
  52.                     Gordon L. Burditt
  53.                     sneaky.lerctr.org!gordon
  54.